// -----------------------------------------------------------------------
// <copyright file="CookiesHelper.cs" company="LBi">
// TODO: Update copyright text.
// </copyright>
// -----------------------------------------------------------------------

using System;
using System.Web;

namespace ColorBox4Sitecore.Helpers
{
    public class CookiesHelper
    {       
        public static void AddToCookie(string cookieName, string value)
        {
            AddToCookie(cookieName, null, value);
        }

        public static void AddToCookie(string cookieName, string key, string value)
        {
            if (HttpContext.Current != null)
            {
                HttpCookie cookie = null;
                if (HttpContext.Current.Request.Cookies[cookieName] == null)
                {
                    cookie = new HttpCookie(cookieName);
                }
                else
                {
                    cookie = HttpContext.Current.Request.Cookies[cookieName];
                }

                cookie.Domain = GetDomain();

                if (key != null)
                {
                    cookie[key] = value;
                }
                else
                {
                    cookie.Value = value;
                }

                cookie.Expires = DateTime.Now.AddYears(1);

                HttpContext.Current.Response.Cookies.Add(cookie);
            }
        }

        public static string GetValue(string cookieName, string key)
        {
            if (HttpContext.Current != null && HttpContext.Current.Request.Cookies[cookieName] != null)
            {
                return HttpContext.Current.Request.Cookies[cookieName].Values[key];
            }
            return null;
        }

        private static string GetDomain()
        {
            return HttpContext.Current.Request.Url.Host.Replace("www", "");
        }
    }
}
